package com.luyou.smart.framewortk;

import com.alibaba.fastjson.JSON;
import com.luyou.smart.framewortk.bean.Data;
import com.luyou.smart.framewortk.bean.Handler;
import com.luyou.smart.framewortk.bean.Param;
import com.luyou.smart.framewortk.bean.View;
import com.luyou.smart.framewortk.helper.BeanHelper;
import com.luyou.smart.framewortk.helper.ConfigHelper;
import com.luyou.smart.framewortk.helper.ControllerHelper;
import com.luyou.smart.framewortk.utils.CodecUtil;
import com.luyou.smart.framewortk.utils.ReflectionUtil;
import com.luyou.smart.framewortk.utils.StreamUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求转发器
 */
public class DispatcherServlet extends HttpServlet {

    /**
     * thymeleaf模版引擎
     */
    private TemplateEngine templateEngine;

    @Override
    public void init(ServletConfig servletConfig){
        //初始化相关Helper
        HelperLoader.init();

        ServletContext servletContext = servletConfig.getServletContext();
        //创建templateServlet
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
        templateResolver.setTemplateMode(TemplateMode.HTML);
        //设置前缀
        templateResolver.setPrefix(ConfigHelper.getAppViewPath());
        //设置后缀
        templateResolver.setSuffix(".html");
        //是否缓存
        templateResolver.setCacheable(true);
        //设置缓存时间
        templateResolver.setCacheTTLMs(60000L);
        templateResolver.setCharacterEncoding("UTF-8");
        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
    }


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求方法与请求路径
        String requestMethod = req.getMethod().toLowerCase();
        String requestPath = req.getPathInfo();
        //获取Action处理器
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if(handler != null){
            //获取Controller类及其Bean实例
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);
            //创建请求参数对象
            Map<String, Object> paramMap = new HashMap<>();
            //表单数据
            Enumeration<String> parameterNames = req.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                String paramValue = req.getParameter(paramName);
                paramMap.put(paramName, paramValue);
            }
            //URL数据
            String body = CodecUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
            if(StringUtils.isNotBlank(body)){
                String[] params = StringUtils.split(body, "&");
                if(ArrayUtils.isNotEmpty(params)){
                    for (String param : params) {
                        String[] array = StringUtils.split(param, "=");
                        if(ArrayUtils.isNotEmpty(array) && array.length == 2){
                            String paramName = array[0];
                            String paramValue = array[1];
                            paramMap.put(paramName, paramValue);
                        }
                    }
                }
            }
            Param param = new Param(paramMap);
            //调用Action方法
            Method actionMethod = handler.getActionMethod();
            Object result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
            if(result instanceof View){
                //返回页面
                View view = (View) result;
                String path = view.getPath();
                resp.setContentType("text/html");
                resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
                WebContext webContext = new WebContext(req, resp, this.getServletContext());
                templateEngine.process(path, webContext, resp.getWriter());
            }else if(result instanceof Data) {
                //返回JSON数据
                Data data = (Data)result;
                Object model = data.getModel();
                if(model != null){
                    resp.setContentType("application/json");
                    resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
                    PrintWriter writer = resp.getWriter();
                    String json = JSON.toJSONString(model);
                    writer.write(json);
                    writer.flush();
                    writer.close();
                }
            }
        }
    }
}
